package com.lvjunxiong.serviceinterface.task;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lvjunxiong.serviceinterface.ServiceDao;
import com.lvjunxiong.serviceinterface.Serviceutil;
import com.lvjunxiong.serviceinterface.tongxun.PhoneModel;
import com.lvjunxiong.serviceinterface.tongxun.R;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.util.List;
import java.util.TimerTask;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.lvjunxiong.serviceinterface.ServiceDao;
import com.lvjunxiong.serviceinterface.Serviceutil;
import com.lvjunxiong.serviceinterface.tongxun.*;

import common.CommModel;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.codehaus.jackson.map.ObjectMapper;

import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.lvjunxiong.serviceinterface.Serviceutil.doPost;

/**
 * Created by lvjunxiong on 2018/11/11.
 */
public class Lock_test extends TimerTask {
    private static final Logger logger = Logger.getLogger(Lock_test.class);
    private ServiceDao dao = new ServiceDao();

    @Override
    public void run() {
        dao.deletesh_suoyin();
        dao.deletesh_suoyin_list();
        ObjectMapper objectMapper = new ObjectMapper();
        HttpURLConnection conn = null;
        String all_tongxunlist = null;
        try {
            all_tongxunlist = doPost("http://app.shuhai.cc/isms/manager/party/all/4028f69f55304e0b01553279b6310042", "");
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(all_tongxunlist);
        JSONObject jo_ = JSONObject.fromObject(all_tongxunlist);
        JSONArray rows = jo_.getJSONArray("rows");
        TongxunDao dao = new TongxunDao();
        TongxunModel model = new TongxunModel();
        List<Tongxun_twoModel> tongxunlist = new ArrayList<Tongxun_twoModel>();
        List<Sh_groupname> list_ = Sh_groupname.getAInitSh_groupnameList();
        Collections.sort(list_, new GroupnameComparetor());

        for (int i = 0; i < list_.size(); i++) {
            Sh_groupname kk = list_.get(i);
            String group_name = kk.getGroupName();
            Tongxun_twoModel mm = new Tongxun_twoModel();
            mm.setId(group_name);
            tongxunlist.add(mm);
        }

        JSONArray jsons = new JSONArray();
        for (int i = 0; i < rows.size(); i++) {
            String res = rows.getString(i);
            JsonParser jps = new JsonParser();
            JsonObject jos = jps.parse(res).getAsJsonObject();
            String gain_id = jos.get("id").getAsString();//获取的id
            String gain_name = jos.get("name").getAsString();//获取的姓名
            String type = jos.get("type").getAsString();//获取的类型
            String parentId = jos.get("parentId").getAsString();//父ID
            String res_ = Serviceutil.converterToFirstSpell(gain_name);
            if ((!type.equals("PARTY_GROUP")) | parentId.equals("4028f69f55304e0b01553279b6310042")) {
                jsons.add(res);
            }
        }
        List<Tongxun_twoModel> list = new ArrayList<Tongxun_twoModel>();
        for (int j = 0; j < tongxunlist.size(); j++) {
            Tongxun_twoModel mm = tongxunlist.get(j);
            String groupName = mm.getId();
            System.out.println(groupName + "====获取到的游标");
            dao.insertSh_suoyin(groupName);
            List<Tongxun_twoListModel> users = new ArrayList<Tongxun_twoListModel>();

            for (int m = 0; m < jsons.size(); m++) {
                String res1 = jsons.getString(m);
                JsonParser jps1 = new JsonParser();
                JsonObject jos1 = jps1.parse(res1).getAsJsonObject();
                String gain_id1 = jos1.get("id").getAsString();//获取的id
                String gain_name1 = jos1.get("name").getAsString();//获取的姓名
                String type1 = jos1.get("type").getAsString();//获取的类型
                String parentId1 = jos1.get("parentId").getAsString();//父ID
                String res_1 = Serviceutil.converterToFirstSpell(gain_name1);
                if (res_1.length() > 0) {
                    String zhuanhua_res = res_1.substring(0, 1);
                    if (groupName.equals(zhuanhua_res)) {
                        System.out.println("==获取到的id==" + gain_id1 + "==获取到的姓名==" + gain_name1 + "==获取到的首字母是==" + zhuanhua_res);
                        Tongxun_twoListModel tongxunListModel = new Tongxun_twoListModel();
                        tongxunListModel.setId(gain_id1);
                        tongxunListModel.setName(gain_name1);
                        int fg = dao.insertSh_suoyin_list(gain_id1, gain_name1, zhuanhua_res);

                        users.add(tongxunListModel);
                        mm.setItems(users);
                    }
                } else {
                    logger.info("不做任何操作，STOP");
                }
            }
            if (users.size() > 0) {
                mm.setEnabled(true);
            } else {
                mm.setEnabled(false);
            }
            List<CommModel> fff = dao.queryYB(groupName);
            if (fff.size() > 0) {
                int i = dao.updatesh_suoyin(groupName, "true");
                if (i > 0) {
                    logger.info("更新索引true成功");
                } else {
                    logger.info("更新索引true失败");
                }
            } else {
                int i = dao.updatesh_suoyin(groupName, "false");
                if (i > 0) {
                    logger.info("更新索引false成功");
                } else {
                    logger.info("更新索引false失败");
                }
            }
            list.add(mm);
        }


        System.out.println("====分栏====");


        List<R> list = dao.qR();
        if (list.size() > 0) {
            System.out.println("有数据");
            for (int i = 0; i < list.size(); i++) {
                String gain_id1 = list.get(i).getId();
                System.out.println("获取到的id：" + gain_id1);
//                    String result_ = null;
//                    try {
//                        result_ = doPost("http://app.shuhai.cc/isms/manager/party/getParent/" + gain_id1, "");
//                    } catch (Exception e) {
//
//                    }
//                    System.out.println(result_ + "==拿到的部门接口数据");
//                    JSONObject jsonObject = JSONObject.fromObject(result_);
//                    String resultStr = jsonObject.toString();
//                    JsonParser jp = new JsonParser();
//                    //将json字符串转化成json对象
//                    JsonObject jo = jp.parse(resultStr).getAsJsonObject();
//                    String corp_name = jo.get("object").getAsJsonObject().get("name").getAsString();
//                    String id_ss = jo.get("object").getAsJsonObject().get("id").getAsString();

                JsonParser jp = new JsonParser();
                CloseableHttpClient httpclient_0 = HttpClients.createDefault();
                HttpPost httpPost_0 = new HttpPost("http://app.shuhai.cc/isms/manager/party/getParent/" + gain_id1);// 创建httpPost
                httpPost_0.setHeader("Accept", "application/json");
                httpPost_0.setHeader("Content-Type", "application/json");
                String charSet_0 = "UTF-8";
                StringEntity entity_0 = new StringEntity("", charSet_0);
                httpPost_0.setEntity(entity_0);
                CloseableHttpResponse response_0 = null;
                String id_ss = "";
                try {
                    response_0 = httpclient_0.execute(httpPost_0);
                    StatusLine status = response_0.getStatusLine();
                    int state = status.getStatusCode();
                    System.out.println(state + "=====");
                    if (state == HttpStatus.SC_OK) {
                        HttpEntity responseEntity_0 = response_0.getEntity();
                        String jsonString = EntityUtils.toString(responseEntity_0);
                        JSONObject jsonObject_2 = JSONObject.fromObject(jsonString);
                        String resultStr_2 = jsonObject_2.toString();
                        JsonParser jp_2 = new JsonParser();
                        JsonObject jo_2 = jp.parse(resultStr_2).getAsJsonObject();
                        JsonObject jo = jp.parse(resultStr_2).getAsJsonObject();
                        String corp_name = jo.get("object").getAsJsonObject().get("name").getAsString();
                        id_ss = jo.get("object").getAsJsonObject().get("id").getAsString();
                    } else {
                        logger.error("请求返回:" + state + "(" + "http://app.shuhai.cc/isms/manager/party/getParent/" + gain_id1 + ")");
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (response_0 != null) {
                        try {
                            response_0.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        httpclient_0.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                logger.info("========================分水岭==========================");
                //String result_two = doPost("http://app.shuhai.cc/isms/manager/party/getParent/" + id_ss, "");

                CloseableHttpClient httpclient = HttpClients.createDefault();
                HttpPost httpPost = new HttpPost("http://app.shuhai.cc/isms/manager/party/getParent/" + id_ss);// 创建httpPost
                httpPost.setHeader("Accept", "application/json");
                httpPost.setHeader("Content-Type", "application/json");
                String charSet = "UTF-8";
                StringEntity entity = new StringEntity("", charSet);
                httpPost.setEntity(entity);
                CloseableHttpResponse response_ = null;
                try {
                    response_ = httpclient.execute(httpPost);
                    StatusLine status = response_.getStatusLine();
                    int state = status.getStatusCode();
                    System.out.println(state + "=====");
                    if (state == HttpStatus.SC_OK) {
                        HttpEntity responseEntity = response_.getEntity();
                        String jsonString = EntityUtils.toString(responseEntity);
                        JSONObject jsonObject_2 = JSONObject.fromObject(jsonString);
                        String resultStr_2 = jsonObject_2.toString();
                        JsonParser jp_2 = new JsonParser();
                        JsonObject jo_2 = jp.parse(resultStr_2).getAsJsonObject();
                        String company_name = jo_2.get("object").getAsJsonObject().get("name").getAsString();//获取到的所属单位名称
                        int k_0 = dao.updatesh_suoyinList(gain_id1, company_name);
                        if (k_0 > 0) {
                            logger.info("更新所属单位名称：" + gain_id1 + "-->成功");
                        } else {
                            logger.info("更新所属单位名称：" + gain_id1 + "-->失败");
                        }

                    } else {
                        logger.error("请求返回:" + state + "(" + "http://app.shuhai.cc/isms/manager/party/getParent/" + id_ss + ")");
                        int k_0 = dao.updatesh_suoyinList(gain_id1, "");
                        if (k_0 > 0) {
                            logger.info("所属单位名称没有：" + gain_id1 + "-->成功");
                        } else {
                            logger.info("所属单位名称没有：" + gain_id1 + "-->失败");
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (response_ != null) {
                        try {
                            response_.close();
                        } catch (IOException e) {
                            logger.info("response_异常了。。。。。。。");
                        }
                    }
                    try {
                        httpclient.close();
                    } catch (IOException e) {
                        logger.info("httpclient请求异常了。。。。。。。");
                    }
                }
            }
        } else {
            System.out.println("无数据");
        }

        logger.info("=======更新部门");
        List<R> list = dao.bm();
        if (list.size() > 0) {
            System.out.println("有数据");
            for (int i = 0; i < list.size(); i++) {
                String hq_id = list.get(i).getId();//获取到的id
                JsonParser jp = new JsonParser();
                CloseableHttpClient httpclient_0 = HttpClients.createDefault();
                HttpPost httpPost_0 = new HttpPost("http://app.shuhai.cc/isms/manager/party/getParent/" + hq_id);// 创建httpPost
                httpPost_0.setHeader("Accept", "application/json");
                httpPost_0.setHeader("Content-Type", "application/json");
                String charSet_0 = "UTF-8";
                StringEntity entity_0 = new StringEntity("", charSet_0);
                httpPost_0.setEntity(entity_0);
                CloseableHttpResponse response_0 = null;
                String id_ss = "";
                try {
                    response_0 = httpclient_0.execute(httpPost_0);
                    StatusLine status = response_0.getStatusLine();
                    int state = status.getStatusCode();
                    System.out.println(state + "=====");
                    if (state == HttpStatus.SC_OK) {
                        HttpEntity responseEntity_0 = response_0.getEntity();
                        String jsonString = EntityUtils.toString(responseEntity_0);
                        JSONObject jsonObject_2 = JSONObject.fromObject(jsonString);
                        String resultStr_2 = jsonObject_2.toString();
                        JsonParser jp_2 = new JsonParser();
                        JsonObject jo_2 = jp.parse(resultStr_2).getAsJsonObject();
                        JsonObject jo = jp.parse(resultStr_2).getAsJsonObject();
                        String corp_name = jo.get("object").getAsJsonObject().get("name").getAsString();
                        id_ss = jo.get("object").getAsJsonObject().get("id").getAsString();
                        //部门名称
                        int j = dao.updateSh_suoyin_listIII(corp_name, hq_id);
                        if(j>0){
                            logger.info("有数据，更新成功");
                        }else{
                            logger.info("有数据，更新失败");
                        }
                    } else {
                        int k = dao.updateSh_suoyin_listII("", hq_id);
                        if (k > 0) {
                            logger.info("无数据，更新成功");
                        } else {
                            logger.info("无数据，更新失败");
                        }
                    }
                } catch (ClientProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (response_0 != null) {
                        try {
                            response_0.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                    try {
                        httpclient_0.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            }
        }

        logger.info("录入手机号");
        dao.deletePhone();
            List<R> list = dao.bmAll();
            if(list.size()>0){
                for (int j = 0; j < list.size(); j++) {
                    String id = list.get(j).getId();
                    String result = null;
                    try {
                        result = Serviceutil.doPost("http://app.shuhai.cc/isms/manager/party/contact/" + id, "");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(result);
                    JSONObject jo_ = JSONObject.fromObject(result);
                    JSONArray rows = jo_.getJSONArray("rows");
                    if(rows.size()>0){
                        int l = dao.updateS_list("true",id);
                        if(l>0){
                            logger.info("更新成功");
                            for (int k = 0; k < rows.size(); k++) {
                                String res = rows.getString(k);
                                JsonParser jps = new JsonParser();
                                JsonObject jos = jps.parse(res).getAsJsonObject();
                                String gain_contactNumber = jos.get("contactNumber").getAsString();//获取的手机号
                                String gain_purposeName = jos.get("purposeName").getAsString();//获取的手机类型
                                System.out.println(gain_contactNumber + "====" + gain_purposeName);
                                int hh = dao.insertP(gain_contactNumber, gain_purposeName, id);
                                if (hh > 0) {
                                    logger.info("插入成功");
                                } else {
                                    logger.info("插入失败");
                                }
                            }
                        }else{
                            logger.info("更新失败");
                            int m = dao.updateS_list("false", id);
                            if(m>0){
                                logger.info("更新失败"+"---->成功");
                            }else{
                                logger.info("更新失败" + "---->失败");
                            }

                        }

                    }

                }
            }
    }
}